package com.dlb.andorid;

import android.content.Context;
import android.util.Log;

import com.kwan.xframe.mvp.model.api.BaseAPIUtil;
import com.kwan.xframe.mvp.model.api.DataSubscriber;
import com.kwan.xframe.mvp.model.api.DataSubscriberListener;
import com.tencent.mm.opensdk.modelbiz.JumpToBizProfile;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;

public class WXLoginUtil extends BaseAPIUtil {

	private String mWXAppId, mSecret;
	private WXLoginListener mLoginListener;
	private Context mContext;
	private IWXAPI mApi;

	public interface WXLoginListener {
		void onGetAccessTokenSuccess(String openid, String access_token, String unionid);

		void onGetAccessTokenFailed();
	}

	public WXLoginUtil(Context context, String appid, String secret) {

		mContext = context;
		mWXAppId = appid;
		mSecret = secret;
		mApi = WXAPIFactory.createWXAPI(App.getInstance(), mWXAppId, true);
		mApi.registerApp(mWXAppId);

	}

	public boolean isWXAppInstalled() {
		return mApi.isWXAppInstalled();
	}

	public void setLoginListener(WXLoginListener mLoginListener) {
		this.mLoginListener = mLoginListener;
	}

	public void doLogin() {

		if (isWXAppInstalled()) {
			Log.e("kwan", "wx doLogin");
			SendAuth.Req req = new SendAuth.Req();
			req.scope = "snsapi_userinfo";
			req.state = "wechat_sdk_demo_test_neng";
			mApi.sendReq(req);

		} else {
			Log.e("kwan", "么有安装");
			//Toast.makeText(mContext, "用户未安装微信", Toast.LENGTH_SHORT).show();
		}
	}

	public void jump() {

		JumpToBizProfile.Req req = new JumpToBizProfile.Req();
		req.toUserName = "要跳转的公众号原始ID"; // 公众号原始ID
		req.extMsg = "";
		req.profileType = JumpToBizProfile.JUMP_TO_NORMAL_BIZ_PROFILE; // 普通公众号
		mApi.sendReq(req);

	}

	public void getAccess_token(String code) {

		TreeMap<String, String> args = new TreeMap<>();
		args.put("appid", mWXAppId);
		args.put("secret", mSecret);
		args.put("code", code);
		args.put("grant_type", "authorization_code");

		Disposable disposable = serverAPI(TYPE_JSON).create(WXLoginUtil.API.class).getAccess_token(args)
				.subscribeOn(Schedulers.io())
				.observeOn(Schedulers.io())
				.subscribeWith(new DataSubscriber<>(new DataSubscriberListener<Object>() {
					@Override
					public void onDataCompleted(int vocational_id, HashMap<String, Object> exData) {

					}

					@Override
					public void onDataError(int vocational_id, HashMap<String, Object> exData, Throwable throwable) {
						Log.e("kwan", "onDataError wx:");
						if (mLoginListener != null)
							mLoginListener.onGetAccessTokenFailed();
					}

					@Override
					public void onDataNext(int vocational_id, HashMap<String, Object> exData, Object data) {
						Log.e("kwan", "onDataNext wx:" + data);
						try {

							JSONObject jsonObject = new JSONObject((String) data);
							String openid = jsonObject.getString("openid").trim();
							String access_token = jsonObject.getString("access_token").trim();
							String unionid = jsonObject.getString("unionid").trim();
							if (mLoginListener != null)
								mLoginListener.onGetAccessTokenSuccess(openid, access_token, unionid);

							// getUserMsg(access_token, openid);

						} catch (JSONException e) {
							e.printStackTrace();
							if (mLoginListener != null)
								mLoginListener.onGetAccessTokenFailed();
						}
					}
				}));
	}


	public void getUserMsg(String access_token, String openid) {

		TreeMap<String, String> args = new TreeMap<>();
		args.put("access_token", access_token);
		args.put("openid", openid);
		args.put("grant_type", "authorization_code");
		Disposable disposable = serverAPI(TYPE_JSON).create(WXLoginUtil.API.class).getUserMsg(args)
				.subscribeOn(Schedulers.io())
				.observeOn(Schedulers.io())
				.subscribeWith(new DataSubscriber<>(new DataSubscriberListener<Object>() {
					@Override
					public void onDataCompleted(int vocational_id, HashMap<String, Object> exData) {
					}

					@Override
					public void onDataError(int vocational_id, HashMap<String, Object> exData, Throwable throwable) {
					}

					@Override
					public void onDataNext(int vocational_id, HashMap<String, Object> exData, Object data) {
						Log.e("kwan", "wx:" + data);
					}
				}));
	}


	public interface API {

		@POST("sns/oauth2/access_token")
		Flowable<String> getAccess_token(@QueryMap Map<String, String> params);

		int ACCESS_TOKEN_VOCATIONAL_ID = 0x000000;

		@POST("sns/userinfo")
		Flowable<String> getUserMsg(@QueryMap Map<String, String> params);

		int USER_MSG_VOCATIONAL_ID = 0x000001;
	}

	@Override
	protected String getBaseUrl() {
		return "https://api.weixin.qq.com/";
	}

	@Override
	protected String getBaseTokenUrl() {
		return null;
	}

	@Override
	protected String getBaseUpLoadUrl() {
		return null;
	}

	@Override
	protected String getToken() {
		return null;
	}
}
